package com.ukao.cashregister.nfc;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;


import com.ukao.cashregister.eventbus.MembershipCardEvent;
import com.ukao.cashregister.eventbus.ReadCardEvent;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.utils.Utils;

import static com.ukao.cashregister.eventbus.ReadCardEvent.Message.READCARD;


@SuppressLint("NewApi")
public class NFCActivity extends Activity {
	protected PendingIntent pendingIntent;
	protected NfcAdapter nfcAdapter;
	private MifareClassic mifareClassic;

	@SuppressLint("NewApi")
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
		pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

		// 检查nfc是否开启
		checkNfc();
		onNewIntent(getIntent());

	}

	private void checkNfc() {
		if (nfcAdapter!=null&&!nfcAdapter.isEnabled()) {
			startActivity(new Intent(
					android.provider.Settings.ACTION_NFC_SETTINGS));
		}
	}



	@SuppressLint("NewApi")
	protected void onResume() {

		super.onResume();
		if (nfcAdapter != null)
			nfcAdapter.enableForegroundDispatch(this, pendingIntent, FILTERS,
					TECHLISTS);

	}

	public static String[][] TECHLISTS;
	@SuppressLint("NewApi")
	public static IntentFilter[] FILTERS;

	static {
		try {
			TECHLISTS = new String[][] { { IsoDep.class.getName() },
					{ NfcV.class.getName() }, { NfcF.class.getName() }, };

			FILTERS = new IntentFilter[] { new IntentFilter(
					NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") };
		} catch (Exception e) {
		}
	}


	@SuppressLint("NewApi")
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (nfcAdapter != null)
			nfcAdapter.disableForegroundDispatch(this);
	}

	@SuppressLint("NewApi")
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {

		} else {
			if (tag != null) {

				// 获取卡类型，根据卡类型可推出卡协议
				String[] techList = tag.getTechList();
				StringBuffer techString = new StringBuffer();
				for (int i = 0; i < techList.length; i++) {
					techString.append(techList[i]);
					techString.append(";\n");
				}
				techString.append(techString.toString());

				// 获取卡id
				byte[] id = tag.getId();
				mifareClassic= MifareClassic.get(tag);
				if (mifareClassic== null) {
					MembershipCardEvent.postNoData(MembershipCardEvent.Message.notFound);
					finish();
					return;
				}
				readCard();





			}

		}
	}

	// converts byte arrays to string
	protected String ByteArrayToHexString(byte[] inarray) {
		int i, j, in;
		String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
				"B", "C", "D", "E", "F" };
		String out = "";
		for (j = 0; j < inarray.length; ++j) {
			in = inarray[j] & 0xff;
			i = (in >> 4) & 0x0f;
			out += hex[i];
			i = in & 0x0f;
			out += hex[i];
		}
		return out;
	}



	public  void  readCard(){
		MifareClassicCard mifareClassicCard = new MifareClassicCard(
				mifareClassic);
		String content = mifareClassicCard.readCarCode(4,
				"31455433494F".trim());
		if ("秘钥错误".equals(content) || "读取失败".equals(content)){
			MembershipCardEvent.postHasData(MembershipCardEvent.Message.fali, content);
			finish();
			return;
		}
		L.i("content="+content);
		MembershipCardEvent.postHasData(MembershipCardEvent.Message.nfc_read, content);

		finish();
	}




}
